package com.eims.sls_app.ui;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.Selection;
import android.text.Spannable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.MySingleton;
import com.android.volley.toolbox.RequestParams;
import com.android.volley.toolbox.StringRequest;
import bls.juejin.cn.R;
import com.eims.sls_app.dataaccess.ChargeActivity;
import com.eims.sls_app.dataaccess.RechargeType;
import com.eims.sls_app.utils.App;
import com.eims.sls_app.utils.RequestUtil;
import com.eims.sls_app.view.MyToast;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONObject;

/**
 * 银联充值
 * 
 * @author SLS003
 */
public class RechargeUPActivity extends MyBaseActivity implements OnClickListener {
	private static final String TAG = "RechargeUPActivity";
	private Activity context = RechargeUPActivity.this;
	private EditText et_money;
	private Button btn_recharge;
	private ImageButton btn_back;
	private TextView tv_name;
	private TextView tv_title;
	private double money;
	// private MyAsynTask myAsynTask;
	private static final String UP_MODEL = "00";// 01、测试环境 00、正式环境

	// private MyHandler myHandler;
	private String opt, auth, info, time, imei, crc;

	// 04-12 15:13:30.124: INFO/System.out(925):
	// 拿到订单信息：partner="2088901133614954"&seller="zhuj@sense.com.cn"&out_trade_no="1000000506"&subject="05FB1E7970C5235A2B"&body="TicketMoney"&total_fee="0.01"&notify_url="http://app.test.sls.net.cn/Home2/Room/OnlinePay/AlipayApp/Notify.aspx"&sign="QKnktGp4KSkV1FpC/rq19gzL5WxL58XNdHdyNEgyvQl+5DAzvHSAsUYtlsujjJfWxTP3FXxUu3BKQfAa3xNDcHQbnn9tr3auVtChY7lTt+Bmd7aAsJKvlpPnTrgaj5goAxvSgCBvmtt6CwPYFU3JzqYXhXOu0Ugn6ubUUn6CU4Y="

	private ProgressDialog mProgress = null;

	private Request jsonObjectRequest;
	private Dialog dialog;

	// 新增控件

	private TextView tvRechargeCj;// 彩金

	private RechargeType rechargeType;

	private List<ChargeActivity> typeList;

	private List<Double> doubleList;
	private DecimalFormat format = new DecimalFormat("#####0.00");
	private double Max;

	private double Min;

	private double dMoney;

	private LinearLayout linear_CJ;
	private Handler handler = new Handler() {
		public void handleMessage(Message msg) {

			switch (msg.what) {

			case 0:

				linear_CJ.setVisibility(View.VISIBLE);
				tvRechargeCj.setVisibility(View.VISIBLE);
				// 0Log.e("ListSize",typeList.size()+"");
				if (typeList.size() > 0) {
					int count = typeList.size();

					for (int i = 0; i < count; i++) {

						if (rechargeType.getGiveType() == 1) {// 定比

							if ((dMoney >= typeList.get(i).getConditionLowest())
									&& (dMoney <= typeList.get(i)
											.getConditionHighest())) {

								tvRechargeCj.setText(format.format(dMoney
										* typeList.get(i).getNumerical()));
								tvRechargeCj.setTextColor(getResources()
										.getColor(R.color.red));
							}

						} else if (rechargeType.getGiveType() == 0) {// 定值

							if ((dMoney >= typeList.get(i).getConditionLowest())
									&& (dMoney <= typeList.get(i)
											.getConditionHighest())) {

								tvRechargeCj.setText(format.format(typeList
										.get(i).getNumerical()));
								tvRechargeCj.setTextColor(getResources()
										.getColor(R.color.red));
							}

						}

					}

				}

				break;

			default:
				break;
			}

		};

	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_recharge);
		findView();
		init();
		setListener();
		// getInitRechargeData();
	}

	private void init() {
		// DecimalFormat df = new DecimalFormat("#####0.00");
		money = 20;
		// et_money.setText(20+"");
		et_money.setSelection(et_money.getText().length());
		// money = Double.parseDouble(et_money.getText().toString());
		typeList = new ArrayList<ChargeActivity>();
		doubleList = new ArrayList<Double>();
	}

	/** 初始化UI */
	private void findView() {
		// myHandler = new MyHandler();
		btn_back = (ImageButton) findViewById(R.id.btn_back);
		et_money = (EditText) this.findViewById(R.id.recahge_et_money);
		btn_recharge = (Button) this.findViewById(R.id.recharge_btn_ok);
		tv_name = (TextView) this.findViewById(R.id.recahge_name2);
		tv_title = (TextView) this.findViewById(R.id.tv_title);
		tv_title.setText("银联充值");
		tv_name.setText(App.user.getName());

		tvRechargeCj = (TextView) findViewById(R.id.tv_recharge_CJ);
		linear_CJ = (LinearLayout) findViewById(R.id.linear_CJ);
	}

	/** 绑定监听 */
	private void setListener() {
		btn_back.setOnClickListener(this);
		btn_recharge.setOnClickListener(this);
		// et_money.addTextChangedListener(watcher);

		et_money.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence arg0, int arg1, int arg2,
					int arg3) {
				// TODO Auto-generated method stub

			}

			@Override
			public void beforeTextChanged(CharSequence arg0, int arg1,
					int arg2, int arg3) {
				// TODO Auto-generated method stub

			}

			@Override
			public void afterTextChanged(Editable s) {

				if (s.length() == 0) {

					tvRechargeCj.setVisibility(View.GONE);
					linear_CJ.setVisibility(View.GONE);

				} else {

					dMoney = Double.parseDouble(et_money.getText().toString()
							.trim());
					if (dMoney < Min) {
						Toast.makeText(context, "你所输入的金额低于活动的最小值" + Min + "元",
								Toast.LENGTH_SHORT).show();
					} else {

						handler.sendEmptyMessage(0);

					}

				}
			}
		});

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.recharge_btn_ok:
			// if (Double.valueOf(et_money.getText().toString()) < 20.00) {
			// MyToast.getToast(context, "充值金额不能低于20.00元").show();
			// // et_money.setText("");
			// // return;
			// }
			// myAsynTask = new MyAsynTask();
			// myAsynTask.execute();
			// btn_recharge.setEnabled(false);
			if (et_money.getText().toString().trim().equals("")) {
				Toast.makeText(RechargeUPActivity.this, "金额为空",Toast.LENGTH_SHORT).show();
				return;
			}

			if (check()) {
				dialog = RequestUtil.createLoadingDialog(context, "正在充值...",
						true);
				dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
					@Override
					public void onCancel(DialogInterface dialog) {
						if (null != jsonObjectRequest)
							jsonObjectRequest.cancel();
					}
				});
				rechargeUPpay();
			}
			break;

		case R.id.btn_back:
			finish();
			break;
		}
	}

	public boolean check() {
		String text = et_money.getText() + "";
		boolean isPass = true;
		if (!"".equals(text)) {
			text = text + ".0";
			double money_text = Double.parseDouble(text);
			if (money_text < 20) {
				et_money.setText(20 + "");
				money = 20;
				MyToast.getToast(RechargeUPActivity.this, "至少充值20元").show();
				isPass = false;
			} else if (money_text > 100000) {// 输入金额大于可用余额
				et_money.setText(100000 + "");
				money = 100000;
				MyToast.getToast(RechargeUPActivity.this, "单笔充值金额最多100000元")
						.show();
				isPass = false;
			}
			setCursorPosition(et_money);
			money = money_text;
		}
		return isPass;
	}

	/**
	 * 银联支付
	 */
	public void rechargeUPpay() {
		MySingleton mySingleton = MySingleton.getInstance(context);
		jsonObjectRequest = new StringRequest(Request.Method.POST,
				App.ylPath, new Response.Listener<String>() {
					@Override
					public void onResponse(String tn) {
						if (null != dialog && dialog.isShowing())
							dialog.dismiss();
						if (RequestUtil.DEBUG) {
							Log.i(TAG, "银联支付获取tn----" + tn);
						}
						String orderInfo;
						try {

							orderInfo = URLDecoder.decode(tn, "UTF-8");
							String order = URLDecoder
									.decode(orderInfo, "UTF-8");
							if (RequestUtil.DEBUG) {
								Log.i(TAG, "银联支付获取订单信息----" + order);
							}
//							UPPayAssistEx.startPayByJAR(context,
//									PayActivity.class, null, null, orderInfo,
//									UP_MODEL);
						} catch (UnsupportedEncodingException e) {
							e.printStackTrace();
							if (RequestUtil.DEBUG) {
								Log.i(TAG, "银联支付充值出错---" + e.getMessage());
							}
							MyToast.getToast(context, "充值失败").show();
						}
					}
				}, new Response.ErrorListener() {

					@Override
					public void onErrorResponse(VolleyError error) {
						if (null != dialog && dialog.isShowing())
							dialog.dismiss();
						RequestParams.convertError(context, error, true);
						if (RequestUtil.DEBUG) {
							String className = error.getClass().getName();
							Log.e(TAG, "className" + className);
							Log.i(TAG, "银联支付充值出错---" + error.getMessage());
						}
						MyToast.getToast(context, "充值失败").show();
					}
				}) {
			@Override
			protected Map<String, String> getParams() throws AuthFailureError {
				String[] names = { "uid", "payMoney" };
				String values[] = { App.user.getUid(), money + "" };
				if (RequestUtil.DEBUG)
					Log.i(TAG, "银联支付uid--" + values[0] + " payMoney--"
							+ values[1]);
				Map<String, String> params = new HashMap<String, String>();
				for (int i = 0; i < names.length; i++) {
					params.put(names[i], values[i]);
				}
				return params;
			}
		};
		jsonObjectRequest.setShouldCache(false);// 是否设置缓存
		mySingleton.addToRequestQueue(jsonObjectRequest);
		dialog.show();
		dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
			@Override
			public void onCancel(DialogInterface dialog) {
				jsonObjectRequest.cancel();// 取消请求
			}
		});
	}

	/** 文本框 监听 */
	private TextWatcher watcher = new TextWatcher() {
		@Override
		public void afterTextChanged(Editable s) {
			String text = s.toString();
			if ("".equals(text)) {
				money = 20;
			}
			// double money_text=Double.parseDouble(text);
			// if(!"".equals(text)&&text.contains(".")){
			// String before_point=text.split("\\.")[0];
			// if(1!=text.split("\\.").length){
			// String point=text.split("\\.")[1];
			// int after_point=Integer.parseInt(point);
			// if(0!=after_point){
			// et_money.setText(before_point+".00");
			// money =Double.parseDouble(before_point+".00");
			// MyToast.getToast(RechargeUPActivity.this,"充值金额只能为整数").show();
			// return;
			// }
			// }
			// }
			// if(money_text<20){
			// et_money.setText("20.00");
			// money = Double.parseDouble(et_money.getText().toString());
			// MyToast.getToast(RechargeUPActivity.this,"至少充值20元").show();
			// return;
			// }else if(money_text>100000){//输入金额大于可用余额
			// et_money.setText(100000.00+"");
			// money =100000d;
			// MyToast.getToast(RechargeUPActivity.this,"单笔充值金额最多100000元").show();
			// return;
			// }
			// setCursorPosition(et_money);
			// money = Double.parseDouble(et_money.getText().toString());
		}

		@Override
		public void beforeTextChanged(CharSequence s, int start, int count,
				int after) {
		}

		@Override
		public void onTextChanged(CharSequence s, int start, int before,
				int count) {
		}
	};

	private void setCursorPosition(EditText et_money) {
		CharSequence spannable = et_money.getText();
		if (spannable != null) {
			Selection.setSelection((Spannable) spannable, spannable.length());
		}
	}

	// /** 关闭进度框 */
	// void closeProgress() {
	// try {
	// if (mProgress != null) {
	// mProgress.dismiss();
	// mProgress = null;
	// }
	// } catch (Exception e) {
	// e.printStackTrace();
	// }
	// }

	// /*** 异步任务 用来后台获取数据 */
	// class MyAsynTask extends AsyncTask<Void, Integer, String> {
	// /** 在后台执行的程序 */
	// String error = "-1001";
	//
	// @Override
	// protected String doInBackground(Void... params) {
	// try {
	// // 准备订单信息
	// String orderInfo = getOrderInfo2();
	// String order = URLDecoder.decode(orderInfo, "UTF-8");
	//
	// System.out.println("充值返回的orderInfo==" + order);
	// if ("-500".equals(orderInfo)) {
	// myHandler.sendEmptyMessage(Integer.parseInt(orderInfo));
	// return null;
	// }
	// UPPayAssistEx.startPayByJAR(context, PayActivity.class, null,
	// null, orderInfo, UP_MODEL);
	// } catch (Exception e) {
	// Log.i("x", "充值出错---" + e.getMessage());
	// MyToast.getToast(context,"充值失败").show();
	// }
	// return null;
	// }
	//
	// @Override
	// protected void onPostExecute(String result) {
	// // TODO Auto-generated method stub
	// super.onPostExecute(result);
	// if (mProgress.isShowing()) {
	// mProgress.dismiss();
	// }
	// }
	//
	// @Override
	// protected void onPreExecute() {
	// // TODO Auto-generated method stub
	// super.onPreExecute();
	// mProgress = new ProgressDialog(context);
	// mProgress.isShowing();
	// }
	// }
	//
	// /**
	// * 拿到传到 充值的数据
	// *
	// * @throws Exception
	// */
	// private String getOrderInfo2() throws Exception {
	// System.out.println("点击了。。");
	// String[] names = { "uid", "paymoney" };
	// String uid = App.user.getUid();
	// String values[] = { uid, money + "" };
	// Log.i(TAG,"id---->"+uid+"\nmoney---->"+money);
	// System.out.println();
	// String tn = HttpUtils.doPost(names, values, App.ylPath);
	// String tn2 = URLDecoder.decode(tn, "UTF-8");
	// System.out.println("充值返回的tn==" + tn2);
	// return tn;
	// }

	@Override
	protected void onActivityResult(int requestCode, final int resultCode,
			Intent data) {
		/*************************************************
		 * 步骤3：处理银联手机支付控件返回的支付结果
		 ************************************************/
		if (data == null) {
			return;
		}
		String msg = "";
		/*
		 * 支付控件返回字符串:success、fail、cancel 分别代表支付成功，支付失败，支付取消
		 */
		String str = data.getExtras().getString("pay_result");
		// mProgress.dismiss();
		if (str.equalsIgnoreCase("success")) {// 支付成功
			msg = "支付成功！";
			MyToast.getToast(context, msg).show();
			double a1 = Double.parseDouble(App.user.getBalance());
			App.user.setBalance(a1
					+ Double.parseDouble(et_money.getText().toString()));
			RechargeUPActivity.this.finish();
			Intent intent = new Intent(getApplicationContext(),
					MainActivity.class);
			RechargeUPActivity.this.startActivity(intent);
			MainActivity.toCenter();
		} else if (str.equalsIgnoreCase("fail")) {
			msg = "支付失败！";
		} else if (str.equalsIgnoreCase("cancel")) {
			msg = "用户取消了支付";
		}
		MyToast.getToast(context, msg).show();

		// AlertDialog.Builder builder = new AlertDialog.Builder(this);
		// builder.setTitle("支付结果通知");
		// builder.setMessage(msg);
		// builder.setNegativeButton("确定", new DialogInterface.OnClickListener()
		// {
		//
		// @Override
		// public void onClick(DialogInterface dialog, int id) {
		// dialog.dismiss();
		// }
		// });
		// builder.create().show();
	}

	// /** 处理页面显示的 */
	// @SuppressLint("HandlerLeak")
	// class MyHandler extends Handler {
	// @Override
	// public void handleMessage(Message msg) {
	// btn_recharge.setEnabled(true);
	// switch (msg.what) {
	// case -500:
	// MyToast.getToast(RechargeUPActivity.this, "连接超时").show();
	// break;
	// case 1:
	// closeProgress();
	// mProgress = BaseHelper.showProgress(RechargeUPActivity.this,
	// null, "正在支付", false, true);
	// break;
	// default:
	// break;
	// }
	// if (myAsynTask != null
	// && myAsynTask.getStatus() == AsyncTask.Status.RUNNING) {
	// myAsynTask.cancel(true); // 如果Task还在运行，则先取消它
	// }
	// super.handleMessage(msg);
	// }
	// }

	@Override
	protected void onNewIntent(Intent intent) {
		setIntent(intent);
		super.onNewIntent(intent);
	}

	private void getInitRechargeData() {

		RequestUtil requestUtil = new RequestUtil(context, false, 0) {

			@Override
			public void responseCallback(JSONObject reponseJson) {

				String StrJson = reponseJson.toString();
				Log.e(TAG, StrJson);
				if (null != reponseJson) {

					rechargeType = JSON
							.parseObject(StrJson, RechargeType.class);

					if (rechargeType.getIsSuccess().equals("true")) {

						typeList = rechargeType.getActiveList();
						if (typeList.size() > 0) {

							for (int i = 0; i < typeList.size(); i++) {

								doubleList.add(typeList.get(i)
										.getConditionLowest());
								doubleList.add(typeList.get(i)
										.getConditionHighest());

							}
							Max = Collections.max(doubleList);
							Log.e("MAX", Max + "");
							Min = Collections.min(doubleList);
							Log.e("MIN", Min + "");
						}

						// Toast.makeText(context, rechargeType.getMsg(),
						// Toast.LENGTH_SHORT).show();

					}

				}

			}

			@Override
			public void responseError(VolleyError error) {

				RequestParams.convertError(context, error, true);

			}
		};

		requestUtil.getRechargeParams71();

	}

	@Override
	public void finish() {
		// TODO Auto-generated method stub
		super.finish();

	}

}
